<template>
  <div class="app-table-toolbar">
    <template v-if="buttonsCount <= limit">
      <el-button v-for="(btn, index) in buttonsDisplay" :key="index" :size="computedSize" type="text" @click="handle(btn.event)">{{ btn.text }}</el-button>
    </template>
    <template v-else>
      <el-button v-for="(btn, index) in buttonsDisplay" :key="index" :size="computedSize" type="text" @click="handle(btn.event)">{{ btn.text }}</el-button>
      <el-dropdown :size="computedSize" @command="handle">
        <span :class="[computedSize ? 'el-dropdown-link--' + computedSize : '']" class="el-dropdown-link">
          更多<i class="el-icon-arrow-down el-icon--right" />
        </span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item v-for="(subBtn, subIndex) in buttonsHide" :key="subIndex + limit" :command="subBtn.event">{{ subBtn.text }}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </template>
  </div>
</template>

<script>
import { isFunction } from './utils'

export default {
  name: 'AppTableToolbar',
  componentName: 'AppTableToolbar',
  inject: ['appTable'],
  props: {
    buttons: {
      type: [Array, Object],
      default() {
        return []
      }
    },
    limit: {
      type: Number,
      default: 3
    },
    rowData: {
      type: Object,
      default() {
        return {}
      }
    },
    rowIndex: {
      type: Number,
      default: -1
    },
    size: {
      type: String,
      default: ''
    }
  },
  computed: {
    computedSize() {
      return this.size || (this.appTable || {}).size
    },
    buttonsCount() {
      return this.buttons.length
    },
    buttonsDisplay() {
      const length = this.buttons.length
      const displayMaxNumber = Math.max(this.limit - 1, 0)
      const displayNumber = length <= this.limit ? length : displayMaxNumber
      return this.buttons.slice(0, displayNumber)
    },
    buttonsHide() {
      const length = this.buttons.length
      const displayMaxNumber = Math.max(this.limit - 1, 0)
      return this.buttons.slice(displayMaxNumber, length)
    }
  },
  methods: {
    handle(event) {
      isFunction(event) && event(this.rowData, this.rowIndex)
    }
  }
}
</script>
